package org.steven.crm.core.service.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.steven.crm.core.cache.RedisCache;
import org.steven.crm.core.utils.http.SimpleHttpClient;
import org.steven.crm.core.utils.wx.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weixin.popular.api.SnsAPI;
import weixin.popular.api.TicketAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.ticket.Ticket;

import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/2/16 16:00
 * @Version 1.0
 */
public class WeixinService {
    private static Logger logger = Logger.getLogger(WeixinService.class);


    /**
     * 获取微信accessToken
     * @param appId
     * @param appSceret
     * @return
     */
    public String getAccessToken(String appId, String appSceret) {
        String accessToken = RedisCache.getAccessToken(appId);
        if (StringUtils.isEmpty(accessToken)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential&appid=" + appId + "&secret=" + appSceret;
            String rsStr = SimpleHttpClient.get(url, null);

            Map<String, Object> rsHash = JSON.parseObject(rsStr, new TypeReference<Map<String, Object>>() {
            });

            accessToken = (String) rsHash.get("access_token");
            if (StringUtils.isEmpty(accessToken)) {
                logger.error("getAccessToken error,errormsg:" + rsHash.get("errmsg")
                        + ",errcode:" + rsHash.get("errcode"));
                return "";
            }

            RedisCache.setAccessToken(appId, accessToken);
        }

        return accessToken;
    }

    public SnsToken getSnsTokenByCode(String appID, String appSecret, String code) {
        SnsToken snsToken = SnsAPI.oauth2AccessToken(appID, appSecret, code);
        return snsToken;
    }

    public String getOauthLink(String returnUrl, String appID) {
        String oauthUrl = SnsAPI.connectOauth2Authorize(appID, returnUrl, false, "");
        logger.info("oauthUrl " + oauthUrl);
        return oauthUrl;
    }

    public String getJsApiSign(String jsApiTicket, String noncestr, String timestamp, String url) {
        try {
            String preSignString = "jsapi_ticket=" + jsApiTicket
                    + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
            String sign = MD5Util.md5BySha1(preSignString, "utf-8");
            return sign;
        } catch (Exception e) {
            return "";
        }
    }

    public String getJSApiTicket(String appId, String accessToken) {
        String ticketValue = RedisCache.getJSApiTicket(appId);
        if (StringUtils.isNotEmpty(ticketValue)) {
            return ticketValue;
        }

        Ticket ticket = TicketAPI.ticketGetticket(accessToken);
        ticketValue = ticket.getTicket() == null ? "" :  ticket.getTicket();
        RedisCache.setJSApiTicket(appId, ticketValue);

        return ticketValue;
    }

    public static void main(String[] args) {
        String token = new WeixinService().getAccessToken("wx0bc8611f98ab972a", "4f62a0aad6d8ab607e3c39813f34f7d9");
        System.out.println(token);
    }
}
